/*
 * @Author: Mr.Song
 * @Date: 2020-07-23 16:34:10
 * @LastEditTime: 2020-07-24 09:55:48
 * @Description: 
 */ 

const  STORAGE_KEY = 'mall';

export default {
  /**
   * @param {key:键，value：内容，[module_name]:模块名称} 
   * @return: 
   * @Description: 存储值
   */  
  setItem(key,value,module_name){
    if (module_name){
      let val = this.getItem(module_name);
      val[key] = value;
      this.setItem(module_name, val);
    }else{
      let val = this.getStorage();
      val[key] = value;
      //为什么使用 window ？ 因为我们是面向模块编程，sessionStorage这个模块上下文可能找不到，虽然它是一个全局变量，所以编译的时候 eslint 可能会报错
      //window 肯定是能被识别的
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
    }
  },
   // 获取某一个模块下面的属性user下面的userName
   getItem(key,module_name){
    if (module_name){
      let val = this.getItem(module_name);
      if(val) return val[key];
    }
    return this.getStorage()[key];
  },
  getStorage(){
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}');
  },
  clear(key, module_name){
    let val = this.getStorage();
    if (module_name){
      if (!val[module_name])return;
      delete val[module_name][key];
    }else{
      delete val[key];
    }
    window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val));
  }
}
